package com.xiyu.service.repository.mailbox.mail;

import com.xiyu.service.model.mailbox.mail.MailboxMailReceiver;
import com.xiyu.service.model.mailbox.mail.MailboxMailReceiverTable;
import org.babyfish.jimmer.spring.repository.JRepository;
import org.babyfish.jimmer.sql.ast.Predicate;
import org.babyfish.jimmer.sql.ast.tuple.Tuple2;

import java.util.List;

public interface MailboxMailReceiverRepository extends JRepository<MailboxMailReceiver, Long> {
    MailboxMailReceiverTable mailboxMailReceiverTable = MailboxMailReceiverTable.$;

    default List<Tuple2<String, String>> listMultiQuery(String multiOption, List<Long> ownerUserId){
        return sql().createQuery(mailboxMailReceiverTable)
                .where(Predicate.or(mailboxMailReceiverTable.address().likeIf(multiOption),
                        mailboxMailReceiverTable.name().likeIf(multiOption)))
                .where(mailboxMailReceiverTable.mail().account().ownerId().in(ownerUserId))
                .select(mailboxMailReceiverTable.name(), mailboxMailReceiverTable.address())
                .distinct().execute();
    }

    default List<Tuple2<String, String>> listQueryByAddress(String address, String name, List<Long> ownerUserId){
        return sql().createQuery(mailboxMailReceiverTable)
                .where(mailboxMailReceiverTable.address().eq(address))
                .where(mailboxMailReceiverTable.name().eqIf(name))
                .where(mailboxMailReceiverTable.mail().account().ownerId().in(ownerUserId))
                .select(mailboxMailReceiverTable.name(), mailboxMailReceiverTable.address())
                .distinct().execute();
    }

    default void updateName(Long mailId, String name){
        sql().createUpdate(mailboxMailReceiverTable)
                .where(mailboxMailReceiverTable.id().eq(mailId))
                .set(mailboxMailReceiverTable.name(), name)
                .execute();
    }

    default List<MailboxMailReceiver> findByMailIdAndType(Long mailId, int type){
        return sql().createQuery(mailboxMailReceiverTable)
                .where(mailboxMailReceiverTable.mailId().eq(mailId))
                .where(mailboxMailReceiverTable.type().eq(type))
                .orderBy(mailboxMailReceiverTable.id())
                .select(mailboxMailReceiverTable).execute();
    }

}